import java.io.*;
import java.util.*;

public class Example {
    public static void main(String[] args) {
        File file = new File("products.txt"); // Assuming the file is named 'products.txt'
        Scanner sc = null;
        FileWriter writer = null;
        int count = 0;
        double sum = 0;

        try {
            // Step 1: Read prices from the file
            sc = new Scanner(file);
            sc.useDelimiter("[^0-9.]+");

            while (sc.hasNextDouble()) {
                double price = sc.nextDouble();
                sum += price;
                count++;
            }

            // Step 2: Calculate average price
            if (count > 0) {
                double averagePrice = sum / count;
                String formattedAverage = String.format("%.2f", averagePrice);
                System.out.println("Average Price: " + formattedAverage + "元");
                // Step 3: Append average price to the original file
                writer = new FileWriter(file, true); // true for appending
                writer.write("\nAverage Price: " + formattedAverage + "元");
                System.out.println("Average Price appended to file.");
            } else {
                System.out.println("No prices found in the file.");
            }

        } catch (IOException e) {
            System.out.println("Error processing file: " + e);
        } finally {
            try {
                if (sc != null) sc.close();
                if (writer != null) writer.close();
            } catch (IOException e) {
                System.out.println("Error closing resources: " + e);
            }
        }
    }
}